package it.orma.iridehr.validators;

import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import it.orma.iridehr.controllers.ricerca.AttitudiniForm;
import it.orma.iridehr.controllers.ricerca.RicercaForm;
import it.orma.iridehr.entities.Attitudine;

import org.apache.commons.lang3.StringUtils;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.binding.validation.ValidationContext;
import org.springframework.stereotype.Component;

@Component
public class RicercaFormValidator {
	public void validate(final RicercaForm form, ValidationContext context) {
		MessageContext messages = context.getMessageContext();
		if (StringUtils.isEmpty(form.getCriteria())){
			messages.addMessage(new MessageBuilder().error().source("criteria").code("error.campo.obbligatorio").build());
		}
		if (form.getTipoRicerca().equals("cercacandidatialfresco")){
			if(StringUtils.isEmpty(form.getQuery())||!StringUtils.isEmpty(form.getQuery())&&!checkTermLength(form.getQuery().trim()))
				messages.addMessage(new MessageBuilder().error().source("query").code("error.campi.corti").arg("2").build());
		}else{
			if(StringUtils.isEmpty(form.getNome())&&StringUtils.isEmpty(form.getCognome())){
				messages.addMessage(new MessageBuilder().error().source("nome").code("error.campo.corto").arg("2").build());
				messages.addMessage(new MessageBuilder().error().source("cognome").code("error.campi.corti").arg("2").build());
			}
			else if(!StringUtils.isEmpty(form.getNome())&&!checkTermLength(form.getNome().trim())){
				messages.addMessage(new MessageBuilder().error().source("nome").code("error.campi.corti").arg("2").build());
			}
			else if(!StringUtils.isEmpty(form.getCognome())&&!checkTermLength(form.getCognome().trim())){
				messages.addMessage(new MessageBuilder().error().source("cognome").code("error.campi.corti").arg("2").build());
			}
			
		}
		
	}

	private boolean checkTermLength(String query) {
		StringTokenizer tokenizer = new StringTokenizer(query.replaceAll(" +", " ")," ");
		while(tokenizer.hasMoreTokens()){
			String token = tokenizer.nextToken();
			if (token.length()<2)
				return false;
		}
		return true;
	}
}
